﻿using CSharpMesInterfaceDLL;
using CSharpStationOperate;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Test
{
    public partial class Form1 : Form
    {
        private string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TemplateConfigPath.txt");
        private FileSystemWatcher _barcodeFileWatcher = null;
        public Form1()
        {
            InitializeComponent();                        
        }

        private DateTime _lastEvent = DateTime.MinValue;
        private void _barcodeFileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            var lastWriteTime = File.GetLastWriteTime(e.FullPath);
            if ((lastWriteTime - _lastEvent).TotalMilliseconds < 100) return;
            _lastEvent = DateTime.Now;
            try
            {
                string barcode = string.Empty;
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        barcode = File.ReadAllText(e.FullPath);
                        break;
                    }
                    catch
                    {
                        System.Threading.Thread.Sleep(200);
                    }
                }                
                if (!string.IsNullOrEmpty(barcode))
                {
                    WriteInfo($"{e.ChangeType.ToString()}/{lastWriteTime.ToLongTimeString()}:{barcode}");
                    ApiPass(barcode);
                }
            }
            catch(Exception ex)
            {
                WriteInfo($"Error: {ex.Message}\r\n{ex.InnerException}");
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                _barcodeFileWatcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory, "Barcode.txt");
                _barcodeFileWatcher.NotifyFilter = NotifyFilters.LastWrite;
                _barcodeFileWatcher.Changed += _barcodeFileWatcher_Changed;
                _barcodeFileWatcher.EnableRaisingEvents = true;
                WriteInfo($"Mes Api server start...");
                var dir = Path.GetDirectoryName(fileName);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                WriteInfo(ex.Message);
            }
            //调用登陆
            //Login();
            //ApiPass("6901232435566");
            #region 获取登录信息的方式
            // string msg, outdata;

            // StationInfo stationInfo = Station.Instance.GetStationInfo();
            // stationInfo.modelinfos[0].model = "CPH2699MX";

            // // 下载文件路径"D:\\OVisionPlusConfig\\ProcessConfig\\" + info.modelinfos[0].model + "\\MePeVariable";
            //int a= Station.Instance.DownloadME_PEConfig(Station.Instance.GetStationInfo(), out msg);

            // //站点：Oper
            // string oper = Station.Instance.GetStationInfo().oper;
            // //站点：Oper
            // string oper_dec = Station.Instance.GetStationInfo().dec;
            // //站点描述
            // string dec = Station.Instance.GetStationInfo().dec;
            // //制造命令
            // string order = Station.Instance.GetStationInfo().order;
            // //站点
            // string section = Station.Instance.GetStationInfo().section;

            // //拉线
            // string line = Station.Instance.GetStationInfo().line;
            // //登录机型
            // string model = Station.Instance.GetMfgPlanInfo().model;
            // //flow
            // string flow = Station.Instance.GetMfgPlanInfo().flow;
            // //factory
            // string factory = Station.Instance.GetLoginInfo().factory;
            // //Udisk
            // string machineId = Station.Instance.UdiskId;
            // //用户账号
            // string user = Station.Instance.GetLoginInfo().user;
            // //是否离线
            // bool offline = Station.Instance.Offline;
            // //是否已经点击上传工艺参数按钮
            // bool IsUploadProcessConfig = Station.Instance.IsUploadProcessConfig;

            // //获取参数下载到本地的路径
            // string processConfigPath = Station.Instance.ProcessConfigPath;
            // //上传参数
            // if (!Station.Instance.UploadConfigForm())
            // {
            //     //
            // }

            #endregion 获取登录信息的方式

            #region 调用MES服务的参考样式,其他接口以此类推
            ////AMES_MOLD_001
            //string postinfo = "{\r\n  \"moldId\": \"B3204468CC40223144031\",\r\n  }";
            //if (!Mes.Inst().NormalApi("ArasCheckMoldValid", postinfo, out outdata, out msg))
            //{
            //}

            ////AMES_MOLD_002
            //postinfo = "{\r\n  \"moldId\": \"B3204468CC40223144031\",\r\n  }";
            //if (!Mes.Inst().NormalApi("ArasCheckMoldMatchInfo", postinfo, out outdata, out msg))
            //{
            //}

            ////AMES_CHECKSN_001
            //postinfo = "{\r\n    \"factory\": " + factory + ",\r\n    \"lotId\": \"F*621019000190TF2405070120010001\",\r\n    \"flow\":" + flow + ", /*非必填*/\r\n    \"lineId\": " + line + ",/*非必填*/\r\n    \"oper\":" + oper + ",\r\n    \"testResult\": \"pass\",/*非必填*/\r\n    \"productModel\": " + model + ",/*必填*/\r\n    \"station\": \"AA\",/*非必填*/\r\n    \"orderId\":" + order + ",/*非必填*/\r\n    \"machineId\":" + machineId + ",/*非必填,设备ID*/\r\n    \"procstep:\"1\"/*必填，1过站检查；2过站*/\r\n}";
            //if (!Mes.Inst().NormalApi("AwipSnEndLotOfflineCheck", postinfo, out outdata, out msg))
            //{

            //}
            #endregion 调用MES服务的参考样式,其他接口以此类推
        }

        /// <summary>
        /// 登陆，选择产品，下载配置文件
        /// </summary>
        private void Login()
        {
            try
            {
                this.BringToFront(); // 窗口置顶 
                if (Station.Instance.LoginMes(out _))
                {
                    //登陆成功
                    //Station.Instance.DownloadME_PEConfig(Station.Instance.GetStationInfo(), out var msg);     // 无需调用该函数
                    //站点：Oper
                    string oper = Station.Instance.GetStationInfo().oper;
                    //拉线
                    string line = Station.Instance.GetStationInfo().line;
                    //登录机型
                    string model = Station.Instance.GetMfgPlanInfo().model;
                    string visionConfigPath = Station.Instance.VisionConfigPath;
                    string msg = $"oper={oper},lineId={line},productModel={model},configPath={visionConfigPath}";
                    if (!string.IsNullOrEmpty(visionConfigPath))
                    {
                        WriteInfo("MES登陆成功");
                        File.WriteAllText(fileName, visionConfigPath);
                    }
                    else
                    {
                        WriteInfo("MES登失败");
                    }
                    WriteInfo(msg);
                    File.WriteAllText(fileName, "D:\\Documents");
                }
            }
            catch (Exception ex)
            {
                WriteInfo($"Login error:{ex.Message}");
            }
        }
        /// <summary>
        ///  调用MES上传过站接口  
        /// </summary>
        /// <param name="post"></param>
        private void ApiPass(string post)
        {
            if(string.IsNullOrEmpty(post)) { return; };
            if(post.Equals("Login"))
            {
                WriteInfo("调用MES登陆");
                Login();
            }
            else
            {
                if (!post.Contains("{"))
                {
                    // {"procstep":1,"productModel":"OPPO R6","lotId":"6901232435566","lineId":"725","oper":"长安测试厂","result":"PASS"}
                    post = string.Format("{{\"procstep\":2,\"productModel\":\"{0}\",\"lotId\":\"{1}\",\"lineId\":\"{2}\",\"oper\":\"{3}\",\"result\":\"PASS\"}}",
                        Station.Instance.GetMfgPlanInfo().model,
                        post,
                        Station.Instance.GetStationInfo().line,
                        Station.Instance.GetStationInfo().oper);
                }
                string msg, outdata;
                //para = "{\r\n  \"moldId\": \"B3204468CC40223144031\",\r\n  }";
                if (!Mes.Inst().NormalApi("CateEndLot", post, out outdata, out msg))
                {
                    WriteInfo($"MES过站调用失败:NormalApi/CateEndLot");
                }
                else
                {
                    WriteInfo("MES过站调用成功");
                }
                WriteInfo($"post:{post}\r\noutdata:{outdata}\r\nmsg:{msg}");
            }          
        }
        private void WriteInfo(string msg)
        {
            if (this.richTextBox1.InvokeRequired)
            {
                this.richTextBox1.Invoke(new Action(delegate
                {
                    this.richTextBox1.AppendText(string.Format("{0}: {1}\r\n", DateTime.Now.ToString("HH:mm:ss fff"), msg));
                    if (this.richTextBox1.TextLength > 80000)
                        this.richTextBox1.Text = "";
                }));
            }
            else
            {
                this.richTextBox1.AppendText(string.Format("{0}: {1}\r\n", DateTime.Now.ToString("HH:mm:ss fff"), msg));
            }
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == SingalNativeMathods.WM_COPYDATA)
            {
                // 解析收到的文件路径
                var cds = (SingalNativeMathods.COPYDATASTRUCT)
                    Marshal.PtrToStructure(m.LParam, typeof(SingalNativeMathods.COPYDATASTRUCT));

                if (cds.lpData != null)
                {
                    try
                    {
                        ApiPass(cds.lpData);
                    }
                    catch (Exception ex)
                    {
                        WriteInfo(ex.ToString());
                    }
                    //this.BringToFront(); // 窗口置顶 
                }
            }
            base.WndProc(ref m);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(_barcodeFileWatcher != null)
            {
                _barcodeFileWatcher.Changed -= _barcodeFileWatcher_Changed;
                _barcodeFileWatcher.Dispose();
            }
        }
    }
    internal class SingalNativeMathods
    {
        public const int WM_COPYDATA = 0x004A;

        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)] public string lpData;
        }

        public static void SendArgsToRunningInstance(string[] args, string mainformTitle)
        {
            IntPtr hWnd = FindWindow(null, mainformTitle); // 匹配主窗口标题
            if (hWnd != IntPtr.Zero && args.Length > 0)
            {
                // 构建消息结构
                var cds = new COPYDATASTRUCT
                {
                    dwData = IntPtr.Zero,
                    cbData = args[0].Length + 1,
                    lpData = args[0]
                };

                // 发送消息
                SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds);
                //SetForegroundWindow(hWnd); // 激活窗口 
            }
        }
    }    
}